let square = document.getElementsByClassName('square'); //正所有方形
const RANGE = 30; //吸附范围

for (let i = 0; i < square.length; i++) {
    square[i].onmousedown = function (e) {
        // 鼠标与盒子左上角的距离
        let deviationX = e.clientX - this.offsetLeft;
        let deviationY = e.clientY - this.offsetTop;
        document.onmousemove = function (e) {
            // 磁性吸附部分
            // 上u 下d 左l 右r
            // 移动后的盒子的位置
            let lux = e.clientX - deviationX; //左上x
            let luy = e.clientY - deviationY; //左上y

            let rux = lux + square[i].offsetWidth; //右上x
            let ruy = luy; //右上y
            let ldx = lux; //左下x
            let ldy = luy - square[i].offsetHeight; //左下y
            let rdx = rux; //右下x
            let rdy = ldy; //右下y
            for (let k = 1; k < square.length; k++) {
                // 所有图形的左上角
                let klux = square[k].offsetLeft; //左上x
                let kluy = square[k].offsetTop; //左上y
                let krux = klux + square[i].offsetWidth; //右上x
                let kruy = kluy; //右上y
                let kldx = klux; //左下x
                let kldy = kluy - square[i].offsetHeight; //左下y
                let krdx = krux; //右下x
                let krdy = kldy; //右下y
                //右吸左,右上<吸的左上 且 右上在吸得50內 且在同一垂直线上,就让左上等于吸得左上减去自己的宽
                if (rux < klux + RANGE && rux > klux - RANGE && ldy < kluy && luy > kldy) {
                    lux = klux - square[i].offsetWidth;
                }
                //左吸右,左上>吸的右上 且 左上在吸的50內 且在同一垂直线上,就让左上等于吸得右上
                if (lux > krux - RANGE && lux < krux + RANGE && ldy < kluy && luy > kldy) {
                    lux = krux;
                }
                //下吸上
                if (luy < krdy + RANGE && luy > krdy - RANGE && rdx > klux && ldx < krux) {
                    luy = krdy;
                }
                //上吸下
                if (ldy > kluy - RANGE && ldy < kluy + RANGE && rdx > klux && ldx < krux) {
                    luy = kluy + square[i].offsetHeight;
                }
            }
            // 定位给盒子定位
            square[i].style.left = lux + 'px';
            square[i].style.top = luy + 'px';
        };

        // 清楚拖拽
        document.onmouseup = function () {
            document.onmousemove = null;
            document.onmouseup = null;
        };
    };
}
